package com.qufadai.framework.demo.tx;

import java.sql.Connection;
import java.sql.DriverManager;

import com.qufadai.framework.Execution;
import com.qufadai.framework.Interceptor;
import com.qufadai.framework.InterceptorChain;
import com.qufadai.framework.InterceptorOrder;

/**
 * Transaction interceptor.
 */
@InterceptorOrder(1)
public class TxInterceptor implements Interceptor {

	static {
		try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }
        catch(ClassNotFoundException e) {
            throw new NoClassDefFoundError("oracle.jdbc.driver.OracleDriver");
        }
	}
	
    public void intercept(Execution execution, InterceptorChain chain) throws Exception {
        Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:XE", "nutzshop", "nutzshop");
        connection.setAutoCommit(false);
        try {
            TxHolder.setCurrentConnection(connection);
            chain.doInterceptor(execution);
            connection.commit();
        }
        catch (Exception e) {
            connection.rollback();
            throw e;
        }
        finally {
            TxHolder.removeCurrentConnection();
        }
    }
}
